/**
 * @author Admilk
 * 编辑于 ad-plugin
 * 单独提取出来请标注作者
 * @version 1.0.0
 */
import md5 from 'md5'
// import common from "../../lib/common/common.js";
import Base from '../model/base/Base.js'
const operationsMap = {
  md5: async (input) => md5(input), // 32小
  md5_up: async (input) => md5(input).toUpperCase(), // 32大
  md5_16: async (input) => md5(input).substr(8, 16), // 16小
  md5_16_up: async (input) => md5(input).substr(8, 16).toUpperCase(), // 16大
  base64: async (input) => Buffer.from(input).toString('base64'),
  '16base64': async (input) => Buffer.from(input, 'hex').toString('base64'),
  unbase64: async (input) => Buffer.from(input, 'base64').toString('utf-8'),
  '16unbase64': async (input) => Buffer.from(input, 'base64').toString('hex')
}
const applyOperations = async (input, operations) => {
  for (const operation of operations) {
    const func = operationsMap[operation.toLowerCase()]
    if (func) {
      input = await func(input)
    }
  }
  return input
}
const logger = global.logger
export class find extends Base {
  constructor () {
    super({
      name: 'ad[查找]',
      dsc: 'find',
      event: 'message',
      priority: -2,
      rule: [
        {
          reg: '^#?查找(共同|相同)?好友',
          fnc: 'czhy'
        },
        {
          reg: '^#?查找',
          fnc: 'cz'
        },
        {
          reg: /^#?(.*)寻人/i,
          fnc: 'xr'
        }
      ]
    })
  }

  async xr (e) {
    const commandPattern = new RegExp(
      `^#?((?:\\s*(?:${Object.keys(operationsMap).join('|')})\\s*)+)寻人`,
      'i'
    )
    const match = e.msg.match(commandPattern)
    if (!match) {
      e.reply('无效的命令格式')
      return
    }
    const operations = match[1].trim().split(/\s+/)
    const input = e.msg.replace(commandPattern, '').trim()
    logger.info(operations)
    const findInGroup = async (gid) => {
      let map
      try {
        map = await Bot.pickGroup(gid).getMemberMap()
      } catch {
        return null
      }
      for (let [id, info] of map) {
        const transformedId = await applyOperations(String(id), operations)
        if (transformedId === input) {
          return String(id)
        }
      }
      return null
    }

    const groupPromises = Array.from(Bot.gl.keys()).map((gid) =>
      findInGroup(gid)
    )
    const results = await Promise.all(groupPromises)

    const foundId = results.find((result) => result !== null)
    if (foundId) {
      e.reply(foundId)
      return true
    } else {
      e.reply('没有找到匹配的QQ')
      return false
    }
  }

  async czhy (e) {
    if (!e.isMaster) return

    let userArray = []
    const numbersStr = e.msg.replace(/#?查找/g, '').replace(/\s+/g, '')
    const numbersMatch = numbersStr.match(/\d+/g)
    if (numbersMatch) {
      userArray.push(...numbersMatch.map((numStr) => Number(numStr)))
    } else {
      userArray.push(e.group_id)
    }

    let msg = []
    logger.mark(userArray)
    let gl = false
    for (const userf of userArray) {
      if (Bot.uin.includes(userf)) continue
      if (Bot.gl.has(userf)) {
        const groupInfo = Bot.gl.get(userf)
        const groupMembers = await Bot.pickGroup(userf).getMemberMap()
        let groupMsg = []
        let groupFound = false
        let notFoundCount = 0

        groupMsg.push(`——群${userf}——`)

        for (const [uid, member] of groupMembers) {
          if (Bot.fl.has(uid)) {
            const userInfo = Bot.fl.get(uid)
            let msg = []
            // msg.push({ type: "image","file":`https://q1.qlogo.cn/g?b=qq&s=0&nk=${uid}`})
            msg.push(`用户${userInfo.user_id}
  昵称: ${userInfo.nickname}
  ${userInfo.remark !== userInfo.nickname ? `备注: ${userInfo.remark}\n` : ''}性别: ${userInfo.sex === 'male' ? '男' : userInfo.sex === 'female' ? '女' : '楠娘'}`)
            groupMsg.push(msg)
            groupFound = true
          } else {
            notFoundCount++
          }
        }

        if (!groupFound) {
          groupMsg.push(
            `在群${userf}的${groupMembers.size}个人中没有找到共同好友`
          )
        }
        groupMsg.push('———————')
        msg.push(...groupMsg)
      }
    }
    if (msg.length == 0) { msg.push(`在${userArray.length}个人中没有找到共同好友`) }
    if (gl) msg.push('已经过滤了触发的群')

    await this.cm.拆分消息(msg, e, 400)
  }

  async cz (e) {
    if (!e.isMaster) return

    let q = 0
    let userArray = []

    for (let msg of e.message) {
      if (msg.type === 'at') userArray.push(msg.qq)
    }

    const numbersStr = e.msg.replace(/#?查找/g, '').replace(/\s+/g, '')
    const numbersMatch = numbersStr.match(/\d+/g)

    if (numbersMatch) {
      userArray.push(...numbersMatch.map((numStr) => Number(numStr)))
    }

    let user = userArray

    if (user.length === 0) {
      if (e.atall || e.msg.includes('all')) {
        let allinfo = await e.group.getMemberMap()
        allinfo.forEach((item) => {
          user.push(item.user_id)
        })
      }
    }

    let msg = []
    logger.mark(user)
    const memberIndex = new Map()
    let gl = false

    const groupPromises = []

    for (const [gid, info] of Bot.gl) {
      if (e.group_id === gid) {
        gl = true
        continue
      }
      q++
      groupPromises.push(
        (async () => {
          try {
            const memberMap = await Bot.pickGroup(gid).getMemberMap()
            memberMap.forEach((item) => {
              if (!memberIndex.has(item.user_id)) {
                memberIndex.set(item.user_id, [])
              }
              memberIndex.get(item.user_id).push({
                gid,
                group_name: info.group_name,
                role: item.role,
                title: item.title
              })
            })
          } catch (err) {}
        })()
      )
    }

    await Promise.all(groupPromises)

    for (const userf of user) {
      if (Bot.uin.includes(userf)) continue

      if (memberIndex.has(userf)) {
        msg.push(`--用户${userf}--`)
        const groups = memberIndex.get(userf)
        for (const group of groups) {
          msg.push(
            `群${group.gid}(${group.group_name})找到用户${userf}\n身份:${group.role == 'admin' ? '群管理' : group.role == 'owner' ? '群主' : '群员'}${group.title != '' ? `\n头衔: ${group.title}` : ''}`
          )
        }
      }
    }

    if (msg.length === 0) msg.push(`在${q}个群中没有找到这个人`)
    if (gl) msg.push('已经过滤了触发的群')

    await this.cm.拆分消息(msg, e, 200)
  }
}
